package com.atguigu.gmall.index.config;

import com.atguigu.gmall.common.bean.ResponseVo;
import com.atguigu.gmall.index.feign.GmallPmsClient;
import com.atguigu.gmall.pms.entity.CategoryEntity;
import com.google.common.hash.BloomFilter;
import org.redisson.api.RBloomFilter;
import org.redisson.api.RedissonClient;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.util.CollectionUtils;

import java.util.List;

@Configuration
public class BloomFilterConfig {
    @Autowired
    RedissonClient redissonClient;
    @Autowired
    GmallPmsClient gmallPmsClient;

    private static final String KEY_PREFIX = "index:cates:";
    @Bean
    public RBloomFilter rbloomFilter(){
        RBloomFilter<Object> bloom = this.redissonClient.getBloomFilter("index:bloom:filter");
        bloom.tryInit(50l,0.03);
        ResponseVo<List<CategoryEntity>> listResponseVo = this.gmallPmsClient.queryCategoriesWithSub(0l);
        List<CategoryEntity> categoryEntities = listResponseVo.getData();
        if (!CollectionUtils.isEmpty(categoryEntities)){
            categoryEntities.forEach(categoryEntity -> {
                bloom.add(KEY_PREFIX+categoryEntity.getId().toString());
            });
        }
        return bloom;
    }
}
